import { Button, Flex, Form, Input, message, Modal, Progress } from 'antd';
import style from '../css/Registerdetails.module.scss'
import { useEffect, useRef, useState } from 'react';
import { useSearchParams } from 'react-router';
import { patientid, registerlistid } from '../utils/request';
import moment from 'moment';
function Registerdetails() {
    const [formOne] = Form.useForm()
    const [params] = useSearchParams()
    const [register,setRegister] = useState({
        Outpatienttype:'',
        visittype:'',
        freetype:'',
        department:'',
        doctor:'',
        date:'',
        timestamp:'',
        invoicecode:'',
        invoicestatus:'',
        status:''
    }) //挂号信息
    const [patientinfo,setPatientinfo] = useState({
        Medicalcard:'',
        Medicalrecord:'',
        name:'',
        sex:'',
        IDtype:'',
        Idcard:'',
        birthDate:'',
        age:'',
        phone:'',
        address:'',
        nowDetail:'',
        relotion:'',
        people:'',
        guardianshipphone:''
    })
    useEffect(()=>{
        registerlistid({
            id:params.get('id')
        }).then(res=>{
            setRegister(res.data[0])
            patientid({
                id:res.data[0].patient_id
            }).then(res=>{
                console.log(res.data)
                setPatientinfo(res.data[0])
            }).catch(err=>{
                console.log(err)
            })
        }).catch(err=>{
            console.log(err)
        })
    },[])
    // 挂号备注的输入框
    const { TextArea } = Input;
    const maxLength = 200; // 设置最大长度为200
    const [value, setValue] = useState('');
    // 计算剩余字符数
    const remainingChars = maxLength - value.length;
    // 开具发票
    const issueinvoice = () => {
        console.log('开具发票')
    }
    // 取消挂号
    const cannel = () => {
        console.log('取消挂号')
        setIsDeleteModalVisible(true)
    }
    // 打印小票
    const [Printreceipts, setPrintreceipts] = useState(false)
    const [percent, setPercent] = useState<number>(0);
    const intervalRef = useRef<number | null>(null);
    const [printlod,setPrintlod] = useState(false)
    const [printtext,setPrinttext] = useState('打印')
    const [close, setClose] = useState(false)
    const [printcount, setCount] = useState<number>(0);
    // 清除进度条定时器
    const clearIntervalIfSet = () => {
        if (intervalRef.current) {
            clearInterval(intervalRef.current);
            intervalRef.current = null;
        }
    };
    const receipt = () => {
        console.log('打印小票')
        setPrintreceipts(true)
    }
    const printOK = () => {
        setPrintlod(true)
        setPrinttext('打印中')
        clearIntervalIfSet(); // 确保没有重复的定时器
        let currentPercent = 0;
        intervalRef.current = setInterval(() => {
            if (currentPercent < 100) {
                currentPercent += 1; // 你可以调整这个值来改变进度条的速度
                setPercent(currentPercent);
            } else {
                clearIntervalIfSet();
                setPrintlod(false)
                setClose(true)
                setCount(prevCount => prevCount + 1); // 使用函数式更新来确保获取最新的count值
            }
        }, 100); // 你可以调整这个值来改变进度条更新的频率
    }
    const PrintCancel = () => {
        setPrintreceipts(false)
        setPercent(0)
        setClose(false)
        setPrinttext('打印')
    }
    // 组件卸载时清除定时器
    useEffect(() => {
        return () => clearIntervalIfSet();
    }, []);


    // 快捷语
    const [qukily] = useState(['不想挂号了', '挂错号了', '其他'])
    const [textarea, setTextarea] = useState('')
    const [isDeleteModalVisible, setIsDeleteModalVisible] = useState(false);
    const [loading, setLoading] = useState(false);
    const settextarea = (txt: string) => {
        setTextarea(txt)
        console.log(textarea)
    }
    const handleOk = () => {
        // console.log('确认')

        formOne.validateFields().then(values => {
            console.log('Validated values: ', values);
            setLoading(true)
            setTimeout(() => {
                setLoading(false)
                setIsDeleteModalVisible(false)
                formOne.resetFields()
                message.success(`注销操作成功！`);
            }, 2000);
        }).catch(info => {
            console.log('Validate Failed:', info);
        });
    };

    const handleCancel = () => {
        console.log('取消')
        setIsDeleteModalVisible(false)
        formOne.resetFields()
        message.warning('已取消操作')
    };


    // 保存
    const save=()=>{
        console.log('保存',value)
    }
    return (
        <>
            <Modal
                onOk={handleOk}
                onCancel={handleCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u268.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>确认取消</span>
                    </div>
                }
                open={isDeleteModalVisible}
                footer={[
                    <Flex key='flex' justify='flex-end'>
                        <Button key="back" onClick={handleCancel} style={{ height: 32, marginRight: 10 }}>
                            取消
                        </Button>,
                        <Button key="submit" type="primary" loading={loading} onClick={handleOk} style={{ height: 32 }}>
                            确认
                        </Button>,
                    </Flex>
                ]}
                width={375}
            >
                <Form
                    form={formOne}
                    style={{
                        marginTop: 20
                    }}
                    initialValues={{ note: textarea }}
                >
                    <Form.Item className={style.itemstyle} name='note'>
                        <Input.TextArea placeholder='请输入挂号取消原因' style={{ height: 80, borderRadius: 0, resize: 'none', margin: 'auto' }} value={textarea} rows={4} />
                    </Form.Item>
                </Form>
                <div className={style.Quicklanguage}>
                    <p>快捷备注语：</p>
                    <ul>
                        {
                            qukily.map(item =>
                                <li key={item} onClick={() => settextarea(item)}>{item}</li>
                            )
                        }
                    </ul>
                </div>
            </Modal>
            {/* 打印小票 */}
            <Modal
                onOk={printOK}
                onCancel={PrintCancel}
                title={
                    <div style={{ display: 'flex', alignItems: 'center' }}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u268.svg" alt="" />
                        <span style={{ marginLeft: 5 }}>打印小票</span>
                    </div>
                }
                open={Printreceipts}
                footer={[
                    <Flex key='flex' justify='space-between' align='center'>
                        <Button className={close?style.close:''} key="submit" type="primary" loading={printlod} onClick={printOK} style={{ height: 32 }}>
                            {printtext}
                        </Button>
                        <Button onClick={PrintCancel} className={close?'':style.close}>关闭</Button>
                        <p>已打印<span style={{color:'#0468ff'}}>{printcount}</span>次</p>
                    </Flex>
                ]}
                width={375}
            >
                <Progress strokeColor='#0468ff' percent={percent} />
            </Modal>
            <div className={style.optionsboxs}>
                <Flex style={{ height: '100%' }} align='center'>
                    <div className={style.options} onClick={() => issueinvoice()}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%8C%82%E5%8F%B7%E8%AF%A6%E6%83%85/u4570.svg" alt="" />
                        <span>开具发票</span>
                    </div>
                    <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%82%A3%E8%80%85%E8%AF%A6%E6%83%85/u2905.svg" alt="" />
                    <div className={style.options+' '+(register.status == '待就诊'?style.show:'')} style={{display:'none'}} onClick={() => cannel()}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%8C%82%E5%8F%B7%E8%AF%A6%E6%83%85/u4573.svg" alt="" />
                        <span>取消挂号</span>
                    </div>
                    <img className={register.status == '待就诊'?style.show:''} style={{display:'none'}} src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%82%A3%E8%80%85%E8%AF%A6%E6%83%85/u2905.svg" alt="" />
                    <div className={style.options} onClick={() => receipt()}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E8%AE%BE%E8%AE%A1%E7%BB%84%E4%BB%B6/u117.svg" alt="" />
                        <span>打印小票</span>
                    </div>
                </Flex>
                <Flex align='center'>
                    <p className={style.resigeter}>挂号状态：</p>
                    <span className={register.status == '待就诊' ? style.bluestatus : register.status == '已就诊' ? style.greenstatus : register.status == '已退号' ? style.orengestatus : style.graystatus} style={{width:10,height:10,borderRadius:'50%',margin:'0 8px'}}></span>
                    <span className={style.status}>{register.status}</span>
                </Flex>
            </div>
            {/* 患者信息 */}
            <div className={style.patientinfo}>
                <div className={style.title}>
                    <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%82%A3%E8%80%85%E8%AF%A6%E6%83%85/u2811.svg" alt="" />
                    <span>患者信息</span>
                </div>
                <div className={style.tablebox}>
                    <table className={style.table}>
                        <tbody>
                            <tr>
                                <th>就诊卡号</th>
                                <td>{patientinfo.Medicalcard}</td>
                                <th>病历号</th>
                                <td>{patientinfo.Medicalrecord}</td>
                                <th>患者姓名</th>
                                <td>{patientinfo.name}</td>
                            </tr>
                            <tr>
                                <th>性别</th>
                                <td>{patientinfo.sex}</td>
                                <th>证件类型</th>
                                <td>{patientinfo.IDtype}</td>
                                <th>证件号</th>
                                <td>{patientinfo.Idcard}</td>
                            </tr>
                            <tr>
                                <th>出生日期</th>
                                <td>{patientinfo.birthDate?moment(patientinfo.birthDate).format("YYYY-MM-DD"):'--'}</td>
                                <th>年龄</th>
                                <td>{patientinfo.age}岁</td>
                                <th>联系电话</th>
                                <td>{patientinfo.phone}</td>
                            </tr>
                            <tr>
                                <th>监护人关系</th>
                                <td>{patientinfo.relotion}</td>
                                <th>监护人</th>
                                <td>{patientinfo.people}</td>
                                <th>监护人电话</th>
                                <td>{patientinfo.guardianshipphone}</td>
                            </tr>
                            <tr>
                                <th>现住地址</th>
                                <td>{patientinfo.address.split(',')[0]+patientinfo.address.split(',')[1]+patientinfo.address.split(',')[2]}</td>
                                <th>现住详细地址</th>
                                <td colSpan={3}>{patientinfo.nowDetail}</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            {/* 挂号信息 */}
            <div className={style.patientinfo}>
                <div className={style.title}>
                    <div className={style.other}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%8C%82%E5%8F%B7%E8%AF%A6%E6%83%85/u4521.svg" alt="" />
                    </div>
                    <span>挂号信息</span>
                </div>
                <div className={style.tablebox}>
                    <table className={style.table}>
                        <tbody>
                            <tr>
                                <th>门诊类型</th>
                                <td>{register.Outpatienttype}</td>
                                <th>费用类型</th>
                                <td>{register.freetype}</td>
                                <th>就诊类型</th>
                                <td>{register.visittype}</td>
                            </tr>
                            <tr>
                                <th>挂号科室</th>
                                <td>{register.department}</td>
                                <th>挂号医生</th>
                                <td>{register.doctor}</td>
                                <th>挂号日期</th>
                                <td>{register.date}</td>
                            </tr>
                            <tr>
                                <th>排队号</th>
                                <td>1号</td>
                                <th>挂号种类</th>
                                <td>主任医师号</td>
                                <th>挂号时间</th>
                                <td>{moment(register.timestamp).format("YYYY-MM-DD HH:mm:ss")}</td>
                            </tr>
                            <tr>
                                <th>挂号金额</th>
                                <td>￥200.00</td>
                                <th>发票号</th>
                                <td>{register.invoicecode?register.invoicecode:'--'}</td>
                                <th>发票状态</th>
                                <td>{register.invoicestatus?'已开具':'未开具'}</td>
                            </tr>
                            <tr>
                                <th>收费员工号</th>
                                <td>SFR001</td>
                                <th>收费员</th>
                                <td>收费员001</td>
                                <th>订单收据号</th>
                                <td>DD20180606175013</td>
                            </tr>
                        </tbody>
                    </table>
                </div>
            </div>
            {/* 挂号备注 */}
            <div className={style.patientinfo}>
                <div className={style.title}>
                    <div className={style.notes}>
                        <img src="https://cdn7.axureshop.com/demo2024/2321849/images/%E6%8C%82%E5%8F%B7%E8%AF%A6%E6%83%85/u4558.svg" alt="" />
                    </div>
                    <span>挂号备注</span>
                </div>
                <div style={{ marginTop: 20 }}>
                    <div style={{ position: 'relative', marginBottom: 30 }}>
                        <TextArea
                            allowClear
                            value={value}
                            onChange={(e) => setValue(e.target.value)}
                            maxLength={maxLength}
                            placeholder="请输入"
                            autoSize={{ minRows: 4, maxRows: 4 }} // 你可以根据需要调整这里的行高
                            style={{ resize: 'none', fontSize: 16 }}
                        />
                        {/* 显示剩余字符提示 */}
                        <div style={{
                            position: 'absolute',
                            bottom: -20,
                            left: 0,
                            color: remainingChars <= 10 ? '#f5222d' : '#c2c2c2', // 当剩余字符少于10时显示为红色
                        }}>
                            您还可以输入 {remainingChars} 个字
                        </div>
                    </div>
                    <Button type='primary' onClick={save}>保存</Button>
                </div>
            </div>
        </>
    );
}

export default Registerdetails;